# 创建系统监控大盘页面
<template>
  <div class="monitor-dashboard">
    <!-- 顶部操作栏 -->
    <div class="dashboard-header">
      <div class="header-left">
        <el-radio-group v-model="refreshInterval" size="small" @change="handleRefreshIntervalChange">
          <el-radio-button label="0">手动刷新</el-radio-button>
          <el-radio-button label="30">30秒</el-radio-button>
          <el-radio-button label="60">1分钟</el-radio-button>
          <el-radio-button label="300">5分钟</el-radio-button>
        </el-radio-group>
        <el-button type="primary" :icon="Refresh" @click="handleRefresh" :loading="refreshing">
          刷新数据
        </el-button>
      </div>
      <div class="header-right">
        <el-button type="success" :icon="Download" @click="handleExportData">
          导出数据
        </el-button>
        <el-button type="warning" :icon="Setting" @click="handleOpenThresholdSettings">
          阈值设置
        </el-button>
      </div>
    </div>

    <!-- 系统状态概览 -->
    <el-row :gutter="20" class="status-overview">
      <el-col :span="6">
        <el-card shadow="hover" class="status-card">
          <template #header>
            <div class="card-header">
              <span>系统运行状态</span>
              <el-tag :type="getSystemStatusType(systemStatus.status)">
                {{ getSystemStatusLabel(systemStatus.status) }}
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="status-item">
              <span class="label">运行时长</span>
              <span class="value">{{ formatUptime(systemStatus.uptime) }}</span>
            </div>
            <div class="status-item">
              <span class="label">系统健康度</span>
              <el-progress
                :percentage="systemStatus.healthScore"
                :status="getHealthStatus(systemStatus.healthScore)"
                :stroke-width="15"
              />
            </div>
            <div class="status-item">
              <span class="label">系统可用性</span>
              <span class="value">{{ systemStatus.availability }}%</span>
            </div>
            <div class="status-item">
              <span class="label">最后更新时间</span>
              <span class="value">{{ formatDateTime(systemStatus.lastUpdateTime) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="status-card">
          <template #header>
            <div class="card-header">
              <span>性能指标</span>
              <el-tag type="info">实时</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="status-item">
              <span class="label">平均响应时间</span>
              <span class="value" :class="getResponseTimeClass(performance.avgResponseTime)">
                {{ performance.avgResponseTime }}ms
              </span>
            </div>
            <div class="status-item">
              <span class="label">系统吞吐量</span>
              <span class="value">{{ performance.throughput }} QPS</span>
            </div>
            <div class="status-item">
              <span class="label">错误率</span>
              <span class="value" :class="getErrorRateClass(performance.errorRate)">
                {{ performance.errorRate }}%
              </span>
            </div>
            <div class="status-item">
              <span class="label">并发用户数</span>
              <span class="value">{{ performance.concurrentUsers }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="status-card">
          <template #header>
            <div class="card-header">
              <span>资源使用</span>
              <el-tag type="info">实时</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="status-item">
              <span class="label">CPU使用率</span>
              <el-progress
                :percentage="resources.cpuUsage"
                :status="getResourceStatus(resources.cpuUsage)"
              />
            </div>
            <div class="status-item">
              <span class="label">内存使用率</span>
              <el-progress
                :percentage="resources.memoryUsage"
                :status="getResourceStatus(resources.memoryUsage)"
              />
            </div>
            <div class="status-item">
              <span class="label">磁盘使用率</span>
              <el-progress
                :percentage="resources.diskUsage"
                :status="getResourceStatus(resources.diskUsage)"
              />
            </div>
            <div class="status-item">
              <span class="label">网络带宽</span>
              <el-progress
                :percentage="resources.networkUsage"
                :status="getResourceStatus(resources.networkUsage)"
              />
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="status-card">
          <template #header>
            <div class="card-header">
              <span>告警信息</span>
              <el-tag :type="getAlertStatusType(alertStatus.status)">
                {{ getAlertStatusLabel(alertStatus.status) }}
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="status-item">
              <span class="label">今日告警</span>
              <span class="value danger">{{ alertStatus.todayCount }}</span>
            </div>
            <div class="status-item">
              <span class="label">未处理告警</span>
              <span class="value warning">{{ alertStatus.pendingCount }}</span>
            </div>
            <div class="status-item">
              <span class="label">平均响应时间</span>
              <span class="value">{{ alertStatus.avgResponseTime }}分钟</span>
            </div>
            <div class="status-item">
              <span class="label">告警解决率</span>
              <span class="value">{{ alertStatus.resolutionRate }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 监控图表 -->
    <el-row :gutter="20" class="monitor-charts">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>系统性能趋势</span>
              <el-radio-group v-model="performanceTimeRange" size="small">
                <el-radio-button label="1h">1小时</el-radio-button>
                <el-radio-button label="6h">6小时</el-radio-button>
                <el-radio-button label="24h">24小时</el-radio-button>
                <el-radio-button label="7d">7天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="performanceChartRef"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>资源使用趋势</span>
              <el-radio-group v-model="resourceTimeRange" size="small">
                <el-radio-button label="1h">1小时</el-radio-button>
                <el-radio-button label="6h">6小时</el-radio-button>
                <el-radio-button label="24h">24小时</el-radio-button>
                <el-radio-button label="7d">7天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="resourceChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="monitor-charts">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>告警趋势分析</span>
              <el-radio-group v-model="alertTimeRange" size="small">
                <el-radio-button label="1h">1小时</el-radio-button>
                <el-radio-button label="6h">6小时</el-radio-button>
                <el-radio-button label="24h">24小时</el-radio-button>
                <el-radio-button label="7d">7天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="alertChartRef"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>系统调用分布</span>
              <el-radio-group v-model="apiTimeRange" size="small">
                <el-radio-button label="1h">1小时</el-radio-button>
                <el-radio-button label="6h">6小时</el-radio-button>
                <el-radio-button label="24h">24小时</el-radio-button>
                <el-radio-button label="7d">7天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="apiChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时告警列表 -->
    <el-card shadow="hover" class="alert-list-card">
      <template #header>
        <div class="card-header">
          <span>实时告警</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleViewAllAlerts">查看全部</el-button>
            <el-button @click="handleRefresh">刷新</el-button>
          </div>
        </div>
      </template>

      <el-table :data="alertList" border v-loading="loading">
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="告警名称" min-width="150" />
        <el-table-column prop="type" label="告警类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getAlertTypeTag(row.type)">{{ getAlertTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="告警级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getAlertLevelTag(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="告警内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="告警时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">详情</el-button>
            <el-button
              v-if="row.status === 'pending'"
              type="primary"
              link
              @click="handleProcess(row)"
            >
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 阈值设置对话框 -->
    <el-dialog
      v-model="thresholdSettingsVisible"
      title="监控指标阈值设置"
      width="600px"
    >
      <el-form :model="thresholdSettings" label-width="120px">
        <el-form-item label="CPU使用率阈值">
          <el-input-number 
            v-model="thresholdSettings.cpu" 
            :min="0" 
            :max="100"
            :step="5"
          />
          <span class="unit">%</span>
        </el-form-item>
        <el-form-item label="内存使用率阈值">
          <el-input-number 
            v-model="thresholdSettings.memory" 
            :min="0" 
            :max="100"
            :step="5"
          />
          <span class="unit">%</span>
        </el-form-item>
        <el-form-item label="磁盘使用率阈值">
          <el-input-number 
            v-model="thresholdSettings.disk" 
            :min="0" 
            :max="100"
            :step="5"
          />
          <span class="unit">%</span>
        </el-form-item>
        <el-form-item label="网络带宽阈值">
          <el-input-number 
            v-model="thresholdSettings.network" 
            :min="0" 
            :max="100"
            :step="5"
          />
          <span class="unit">%</span>
        </el-form-item>
        <el-form-item label="响应时间阈值">
          <el-input-number 
            v-model="thresholdSettings.responseTime" 
            :min="0" 
            :max="10000"
            :step="100"
          />
          <span class="unit">ms</span>
        </el-form-item>
        <el-form-item label="错误率阈值">
          <el-input-number 
            v-model="thresholdSettings.errorRate" 
            :min="0" 
            :max="100"
            :step="1"
          />
          <span class="unit">%</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="thresholdSettingsVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveThresholdSettings">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导出数据对话框 -->
    <el-dialog
      v-model="exportDialogVisible"
      title="导出监控数据"
      width="500px"
    >
      <el-form :model="exportSettings" label-width="100px">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="exportSettings.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="exportTimeShortcuts"
          />
        </el-form-item>
        <el-form-item label="数据类型">
          <el-checkbox-group v-model="exportSettings.dataTypes">
            <el-checkbox label="system">系统状态</el-checkbox>
            <el-checkbox label="performance">性能指标</el-checkbox>
            <el-checkbox label="resources">资源使用</el-checkbox>
            <el-checkbox label="alerts">告警信息</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportSettings.format">
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="csv">CSV</el-radio>
            <el-radio label="json">JSON</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleExport" :loading="exporting">
            开始导出
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh, Download, Setting } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  getSystemStatus,
  getSystemPerformance,
  getSystemResources,
  getAlertStatus,
  getAlertList,
  getPerformanceTrend,
  getResourceTrend,
  getAlertTrend,
  getApiDistribution,
  exportSystemLogs,
  updateSystemConfig,
  getSystemConfig
} from '@/api/message'

const router = useRouter()

// 系统状态数据
const systemStatus = reactive({
  status: 'normal',
  uptime: 0,
  healthScore: 0,
  availability: 0,
  lastUpdateTime: ''
})

// 性能指标数据
const performance = reactive({
  avgResponseTime: 0,
  throughput: 0,
  errorRate: 0,
  concurrentUsers: 0
})

// 资源使用数据
const resources = reactive({
  cpuUsage: 0,
  memoryUsage: 0,
  diskUsage: 0,
  networkUsage: 0
})

// 告警状态数据
const alertStatus = reactive({
  status: 'normal',
  todayCount: 0,
  pendingCount: 0,
  avgResponseTime: 0,
  resolutionRate: 0
})

// 图表相关
const performanceChartRef = ref(null)
const resourceChartRef = ref(null)
const alertChartRef = ref(null)
const apiChartRef = ref(null)
let performanceChart = null
let resourceChart = null
let alertChart = null
let apiChart = null

// 时间范围选择
const performanceTimeRange = ref('1h')
const resourceTimeRange = ref('1h')
const alertTimeRange = ref('1h')
const apiTimeRange = ref('1h')

// 告警列表数据
const alertList = ref([])
const loading = ref(false)

// 刷新控制
const refreshInterval = ref('30')
const refreshing = ref(false)
let refreshTimer = null

// 阈值设置
const thresholdSettingsVisible = ref(false)
const thresholdSettings = reactive({
  cpu: 80,
  memory: 85,
  disk: 90,
  network: 75,
  responseTime: 1000,
  errorRate: 5
})

// 导出设置
const exportDialogVisible = ref(false)
const exporting = ref(false)
const exportSettings = reactive({
  timeRange: [],
  dataTypes: ['system', 'performance', 'resources', 'alerts'],
  format: 'excel'
})

// 导出时间快捷选项
const exportTimeShortcuts = [
  {
    text: '最近1小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000)
      return [start, end]
    }
  },
  {
    text: '最近24小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24)
      return [start, end]
    }
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  }
]

// 初始化
onMounted(async () => {
  await initCharts()
  await loadDashboardData()
  await loadThresholdSettings()
  
  // 设置定时刷新
  handleRefreshIntervalChange(refreshInterval.value)
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  destroyCharts()
})

// 初始化图表
const initCharts = async () => {
  // 初始化性能趋势图
  performanceChart = echarts.init(performanceChartRef.value)
  performanceChart.setOption({
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['响应时间', '吞吐量', '错误率']
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '响应时间(ms)',
        position: 'left'
      },
      {
        type: 'value',
        name: '吞吐量/错误率',
        position: 'right'
      }
    ],
    series: [
      {
        name: '响应时间',
        type: 'line',
        data: []
      },
      {
        name: '吞吐量',
        type: 'line',
        yAxisIndex: 1,
        data: []
      },
      {
        name: '错误率',
        type: 'line',
        yAxisIndex: 1,
        data: []
      }
    ]
  })

  // 初始化资源趋势图
  resourceChart = echarts.init(resourceChartRef.value)
  resourceChart.setOption({
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['CPU', '内存', '磁盘', '网络']
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: '使用率(%)'
    },
    series: [
      {
        name: 'CPU',
        type: 'line',
        data: []
      },
      {
        name: '内存',
        type: 'line',
        data: []
      },
      {
        name: '磁盘',
        type: 'line',
        data: []
      },
      {
        name: '网络',
        type: 'line',
        data: []
      }
    ]
  })

  // 初始化告警趋势图
  alertChart = echarts.init(alertChartRef.value)
  alertChart.setOption({
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['告警数量', '已处理', '未处理']
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '告警数量',
        type: 'line',
        data: []
      },
      {
        name: '已处理',
        type: 'line',
        data: []
      },
      {
        name: '未处理',
        type: 'line',
        data: []
      }
    ]
  })

  // 初始化API分布图
  apiChart = echarts.init(apiChartRef.value)
  apiChart.setOption({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

// 销毁图表
const destroyCharts = () => {
  performanceChart?.dispose()
  resourceChart?.dispose()
  alertChart?.dispose()
  apiChart?.dispose()
  window.removeEventListener('resize', handleResize)
}

// 加载仪表盘数据
const loadDashboardData = async () => {
  try {
    // 加载基础数据
    const [statusRes, performanceRes, resourcesRes, alertStatusRes] = await Promise.all([
      getSystemStatus(),
      getSystemPerformance(),
      getSystemResources(),
      getAlertStatus()
    ])

    // 更新系统状态
    Object.assign(systemStatus, statusRes.data)
    
    // 更新性能指标
    Object.assign(performance, performanceRes.data)
    
    // 更新资源使用
    Object.assign(resources, resourcesRes.data)
    
    // 更新告警状态
    Object.assign(alertStatus, alertStatusRes.data)

    // 加载图表数据
    await Promise.all([
      updatePerformanceChart(),
      updateResourceChart(),
      updateAlertChart(),
      updateApiChart()
    ])

    // 加载告警列表
    await loadAlertList()
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
    ElMessage.error('加载仪表盘数据失败')
  }
}

// 更新性能趋势图
const updatePerformanceChart = async () => {
  if (!performanceChart) return
  try {
    const res = await getPerformanceTrend({ timeRange: performanceTimeRange.value })
    performanceChart.setOption({
      xAxis: {
        data: res.data.times
      },
      series: [
        {
          data: res.data.responseTimes
        },
        {
          data: res.data.throughputs
        },
        {
          data: res.data.errorRates
        }
      ]
    })
  } catch (error) {
    console.error('更新性能趋势图失败:', error)
  }
}

// 更新资源趋势图
const updateResourceChart = async () => {
  if (!resourceChart) return
  try {
    const res = await getResourceTrend({ timeRange: resourceTimeRange.value })
    resourceChart.setOption({
      xAxis: {
        data: res.data.times
      },
      series: [
        {
          data: res.data.cpuUsage
        },
        {
          data: res.data.memoryUsage
        },
        {
          data: res.data.diskUsage
        },
        {
          data: res.data.networkUsage
        }
      ]
    })
  } catch (error) {
    console.error('更新资源趋势图失败:', error)
  }
}

// 更新告警趋势图
const updateAlertChart = async () => {
  if (!alertChart) return
  try {
    const res = await getAlertTrend({ timeRange: alertTimeRange.value })
    alertChart.setOption({
      xAxis: {
        data: res.data.times
      },
      series: [
        {
          data: res.data.totalCounts
        },
        {
          data: res.data.processedCounts
        },
        {
          data: res.data.pendingCounts
        }
      ]
    })
  } catch (error) {
    console.error('更新告警趋势图失败:', error)
  }
}

// 更新API分布图
const updateApiChart = async () => {
  if (!apiChart) return
  try {
    const res = await getApiDistribution({ timeRange: apiTimeRange.value })
    apiChart.setOption({
      series: [
        {
          data: res.data.distribution
        }
      ]
    })
  } catch (error) {
    console.error('更新API分布图失败:', error)
  }
}

// 加载告警列表
const loadAlertList = async () => {
  try {
    loading.value = true
    const res = await getAlertList({ page: 1, pageSize: 10 })
    alertList.value = res.data.list
  } catch (error) {
    console.error('加载告警列表失败:', error)
    ElMessage.error('加载告警列表失败')
  } finally {
    loading.value = false
  }
}

// 工具方法
const getSystemStatusType = (status) => {
  const map = {
    normal: 'success',
    warning: 'warning',
    error: 'danger'
  }
  return map[status] || 'info'
}

const getSystemStatusLabel = (status) => {
  const map = {
    normal: '正常',
    warning: '警告',
    error: '异常'
  }
  return map[status] || status
}

const getHealthStatus = (score) => {
  if (score >= 90) return 'success'
  if (score >= 70) return 'warning'
  return 'exception'
}

const getResourceStatus = (usage) => {
  if (usage >= 90) return 'exception'
  if (usage >= 70) return 'warning'
  return 'success'
}

const getResponseTimeClass = (time) => {
  if (time >= 1000) return 'danger'
  if (time >= 500) return 'warning'
  return 'success'
}

const getErrorRateClass = (rate) => {
  if (rate >= 5) return 'danger'
  if (rate >= 1) return 'warning'
  return 'success'
}

const getAlertStatusType = (status) => {
  const map = {
    normal: 'success',
    warning: 'warning',
    error: 'danger'
  }
  return map[status] || 'info'
}

const getAlertStatusLabel = (status) => {
  const map = {
    normal: '正常',
    warning: '警告',
    error: '异常'
  }
  return map[status] || status
}

const getAlertTypeTag = (type) => {
  const map = {
    system: 'danger',
    business: 'warning',
    performance: 'info',
    security: 'error'
  }
  return map[type] || 'info'
}

const getAlertTypeLabel = (type) => {
  const map = {
    system: '系统告警',
    business: '业务告警',
    performance: '性能告警',
    security: '安全告警'
  }
  return map[type] || type
}

const getAlertLevelTag = (level) => {
  const map = {
    严重: 'danger',
    高: 'error',
    中: 'warning',
    低: 'info'
  }
  return map[level] || 'info'
}

const getStatusTag = (status) => {
  const map = {
    pending: 'warning',
    processing: 'primary',
    resolved: 'success',
    closed: 'info'
  }
  return map[status] || 'info'
}

const getStatusLabel = (status) => {
  const map = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已解决',
    closed: '已关闭'
  }
  return map[status] || status
}

const formatUptime = (seconds) => {
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  return `${days}天${hours}小时${minutes}分钟`
}

const formatDateTime = (timestamp) => {
  return new Date(timestamp).toLocaleString()
}

// 事件处理
const handleResize = () => {
  performanceChart?.resize()
  resourceChart?.resize()
  alertChart?.resize()
  apiChart?.resize()
}

const handleViewAllAlerts = () => {
  router.push('/message/alert/history')
}

const handleRefresh = () => {
  loadDashboardData()
}

const handleViewDetail = (row) => {
  router.push({
    path: '/message/alert/detail',
    query: { id: row.id }
  })
}

const handleProcess = (row) => {
  router.push({
    path: '/message/alert/process',
    query: { id: row.id }
  })
}

// 监听时间范围变化
watch(performanceTimeRange, () => {
  updatePerformanceChart()
})

watch(resourceTimeRange, () => {
  updateResourceChart()
})

watch(alertTimeRange, () => {
  updateAlertChart()
})

watch(apiTimeRange, () => {
  updateApiChart()
})

// 处理刷新间隔变化
const handleRefreshIntervalChange = (value) => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  
  if (value !== '0') {
    refreshTimer = setInterval(() => {
      handleRefresh()
    }, parseInt(value) * 1000)
  }
}

// 加载阈值设置
const loadThresholdSettings = async () => {
  try {
    const res = await getSystemConfig()
    const config = res.data.monitorThresholds || {}
    Object.assign(thresholdSettings, config)
  } catch (error) {
    console.error('加载阈值设置失败:', error)
  }
}

// 保存阈值设置
const handleSaveThresholdSettings = async () => {
  try {
    await updateSystemConfig({
      monitorThresholds: thresholdSettings
    })
    ElMessage.success('阈值设置保存成功')
    thresholdSettingsVisible.value = false
  } catch (error) {
    console.error('保存阈值设置失败:', error)
    ElMessage.error('保存阈值设置失败')
  }
}

// 打开阈值设置
const handleOpenThresholdSettings = () => {
  thresholdSettingsVisible.value = true
}

// 处理导出数据
const handleExportData = () => {
  exportDialogVisible.value = true
}

// 执行导出
const handleExport = async () => {
  if (exporting.value) return
  
  if (!exportSettings.timeRange || exportSettings.timeRange.length !== 2) {
    ElMessage.warning('请选择导出时间范围')
    return
  }
  
  if (exportSettings.dataTypes.length === 0) {
    ElMessage.warning('请选择要导出的数据类型')
    return
  }
  
  exporting.value = true
  try {
    const params = {
      startTime: exportSettings.timeRange[0].toISOString(),
      endTime: exportSettings.timeRange[1].toISOString(),
      dataTypes: exportSettings.dataTypes.join(','),
      format: exportSettings.format
    }
    
    const res = await exportSystemLogs(params)
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `系统监控数据_${new Date().getTime()}.${exportSettings.format}`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('数据导出成功')
    exportDialogVisible.value = false
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出数据失败')
  } finally {
    exporting.value = false
  }
}
</script>

<style lang="scss" scoped>
.monitor-dashboard {
  padding: 20px;
  
  .dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .header-right {
      display: flex;
      gap: 10px;
    }
  }
  
  .status-overview {
    margin-bottom: 20px;
    
    .status-card {
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      
      .card-content {
        .status-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 15px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .label {
            color: #606266;
          }
          
          .value {
            font-weight: bold;
            
            &.danger {
              color: #f56c6c;
            }
            
            &.warning {
              color: #e6a23c;
            }
            
            &.success {
              color: #67c23a;
            }
          }
        }
      }
    }
  }
  
  .monitor-charts {
    margin-bottom: 20px;
    
    .chart-card {
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      
      .chart-container {
        height: 300px;
      }
    }
  }
  
  .alert-list-card {
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .unit {
    margin-left: 8px;
    color: #909399;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style> 